#include "util.hpp"
volatile bool quit = false;
void Usage(std::string proc)
{
    std::cerr << "Usage:\n\t" << proc << " ip port" << std::endl;
    std::cerr << "exmaple:\n\t" << proc << " 127.0.0.11 8080 \n"
              << std::endl;
}

//./clientTcp serverIp serverPort
int main(int argc, const char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t serverPort = atoi(argv[2]);
    std::string serverIp = argv[1];
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        std::cerr << "socket: " << strerror(errno) << std::endl;
        exit(SOCKET_ERR);
    }
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverPort);
    inet_aton(serverIp.c_str(), &server.sin_addr);
    if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0)
    {
        std::cerr << "connect: " << strerror(errno) << std::endl;
        exit(CONN_ERR);
    }
    std::cout << "info : connect success: " << sock << std::endl;
    std::string message;
    while (!quit)
    {
        message.clear();
        std::cout << "请输入表达式>>> ";//1+1
        getline(std::cin, message); // std:: ???
        if (strcasecmp(message.c_str(), "quit") == 0)
        {
            quit = true;
            continue;
        }
        // 加码
        Request req;
        //将字符串"1+1"通过makeReuquest函数—>req结构体
        if(!makeRequest(message,&req))
        {
            continue;
        }
        //std::cout<<"req: "<<req.x_<<req.op_<<req.y_<<std::endl;
        std::string package;
        req.serialize(package);
        std::cout<<"package~: "<<package<<std::endl;
        package = encode(package, package.size());
        ssize_t s = write(sock, package.c_str(), package.size());
        if (s > 0)
        {
            char buff[1024];
            ssize_t s = read(sock, buff, sizeof(buff) - 1);
            if (s > 0)
                buff[s] = 0;
            std::string echoPackage = buff;
            Respond resp;
            uint32_t len = 0;
            echoPackage = decode(echoPackage, &len);
            if (len > 0)
            {
                if(resp.deserialize(echoPackage))
                {
                    printf("[exitcode: %d] %d\n", resp.exitCode_, resp.result_);
                }
            }
        }
        else
        {
            break;
        }
    }
    close(sock);
    return 0;
}